package com.imessage.action.business.wuma;

import com.bean.BusinessApple;
import com.bean.BusinessWuma;
import com.imessage.comm.Constants;
import com.imessage.type.BusinessAppleState;
import com.imessage.type.BusinessWumaState;
import com.imessage.utils.DateUtil;
import com.imessage.utils.StrUtil;
import com.imessage.vo.WumaVo;
import com.imessage.web.Page;
import io.ebean.Expression;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/admin/wuma")
public class WumaAction extends WumaBaseAction {

    /**
     * 列表数据,搜索数据
     */
    @RequestMapping(value = "")
    public Object run(WumaVo wumaVo) {
        List<Expression> expressionList = new ArrayList<>();
        setExpressionList(expressionList, wumaVo);
        Page<BusinessWuma> page = baseService.findPage(BusinessWuma.class, expressionList,
                null, getOrder(wumaVo.getOrders()), wumaVo.getPageCurrent(),
                wumaVo.getPageSize());
        return page;
    }


    /**
     * 添加修改界面
     */
    @RequestMapping(value = "/initpage")
    public ModelAndView initpage(
            @RequestParam(name = "req_id", required = true) String id) {
        ModelAndView modelAndView = new ModelAndView();
        BusinessWuma wuma = new BusinessWuma();
        if (StringUtils.isNotBlank(id)) {
            wuma = baseService.findById(BusinessWuma.class, id);
            modelAndView.setViewName("admin/business/wuma/modify");
        } else {
            modelAndView.setViewName("admin/business/wuma/add");
        }
        setModelAndView(modelAndView, wuma);
        return modelAndView;
    }


    /**
     * 添加
     */
    @RequestMapping(value = "/add")
    public Object add(WumaVo wumaVo) {
        wumaVo.setMac(wumaVo.getMac().toUpperCase());
        String msg=checkData(wumaVo,null);
        if(StringUtils.isNotBlank(msg)){
            return getJsonForErr(msg, datagrid);
        }
        BusinessWuma wuma = new BusinessWuma();
        setWuma(wumaVo, wuma);
        wuma.setState(BusinessWumaState.init);
        int state = baseService.saveObject(wuma);
        if (state == Constants.STATE_OPERATOR_SUCC) {
            return getJsonForSucc("", datagrid);
        }
        return getJsonForErr("", datagrid);
    }




    /**
     * 修改
     */
    @RequestMapping(value = "/modify")
    public Object modify(WumaVo wumaVo) {
        BusinessWuma wuma = baseService.findById(BusinessWuma.class, wumaVo.getId());
        String msg=checkData(wumaVo,wuma);
        if(StringUtils.isNotBlank(msg)){
            return getJsonForErr(msg, datagrid);
        }
        setWuma(wumaVo, wuma);
        int state = baseService.updateObject(wuma);
        if (state == Constants.STATE_OPERATOR_SUCC) {
            return wuma;
        }
        return getJsonForErr("", datagrid);
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/del")
    public Object del(
            @RequestParam(name = "id", required = true) String ids) {
        int state = Constants.STATE_OPERATOR_LOST;
        for (String id : ids.split(",")) {
            BusinessWuma wuma = baseService.findById(BusinessWuma.class, id);
            wuma.setBusinessApple(null);
            state = baseService.delObject(wuma);
        }
        if (state == Constants.STATE_OPERATOR_SUCC) {
            return getJsonForSucc("", datagrid);
        }
        return getJsonForErr("", datagrid);
    }


    @RequestMapping(value = "/initimp")
    public ModelAndView initimp() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("action", "/admin/wuma/imp");
        modelAndView.addObject("templeturl","/static/file/wumatemplet.xls");
        modelAndView.setViewName("admin/comm/imp");
        return modelAndView;
    }

    @RequestMapping(value = "/imp")
    public Object imp(MultipartFile upfile){
        String filePath=fileUpload(upfile);
        if(StringUtils.isBlank(filePath)){
            return getJsonForErr("上传文件为空或者格式不正确,只支持xls、xlsx格式", datagrid);
        }
        if(saveExcel(filePath)){
            return getJsonForSucc("上传成功", datagrid);
        }
        return getJsonForErr("上传失败", datagrid);
    }


    @ResponseBody
    @RequestMapping(value = "/download",method = RequestMethod.GET)
    public void download(HttpServletResponse response,
                    @RequestParam("id") long id) {
        BusinessWuma businessWuma= baseService.findById(BusinessWuma.class, id);
        if(businessWuma==null){
            return ;
        }
        if(StringUtils.isBlank(businessWuma.getConfigData())){
            return ;
        }
        ByteArrayOutputStream bo =null;
        try{
            bo=new ByteArrayOutputStream();
            bo.write(businessWuma.getConfigData().getBytes());
            response.setHeader("Content-Disposition", "attachment; filename=" +
                    businessWuma.getId()+".txt" );
            Integer contentLength = bo.size();
            response.setHeader("content-length", contentLength + "");
            response.getOutputStream().write(bo.toByteArray());
        }catch (Exception e){
            log.error("", e);
        }finally {
            if(bo!=null){
                try{
                    bo.close();
                }catch (Exception e){
                    log.error("", e);
                }
            }
        }
    }


    /**
     * 批量状态
     */
    @RequestMapping(value = "/state")
    public Object state(
            @RequestParam(name = "id", required = true) String ids,
            @RequestParam(name = "state", required = true) String state) {
        int result = Constants.STATE_OPERATOR_LOST;
        for (String id : ids.split(",")) {
            BusinessWuma wuma = baseService.findById(BusinessWuma.class, id);
            wuma.setState(BusinessWumaState.fromValue(state));
            result = baseService.updateObject(wuma);
        }
        if (result == Constants.STATE_OPERATOR_SUCC) {
            return getJsonForSucc("", datagrid);
        }
        return getJsonForErr("", datagrid);
    }



}
